package com.djmw.mouse.service.account;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import com.djmw.mouse.entity.HrUser;
import com.djmw.mouse.repository.HrUserDao;
import com.djmw.mouse.service.ServiceException;

/**
 * 用户管理类.
 * 
 * @author michael
 */
// Spring Service Bean的标识.
@Component
@Transactional(readOnly = true)
public class HrAccountService extends AccountService {

	@Autowired
	private HrUserDao hrUserDao;

	@Override
	public List<HrUser> getAllUser() {
		return (List<HrUser>) hrUserDao.findAll();
	}

	@Override
	public HrUser getUser(Long id) {
		return hrUserDao.findOne(id);
	}

	@Override
	public HrUser findUserByLoginName(String loginName) {
		return hrUserDao.findByLoginName(loginName);
	}

	public Page<HrUser> getCompanyAccount(Long companyId) {
		PageRequest pageRequest = new PageRequest(0, 20, new Sort(Direction.ASC, "loginName"));
		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
		filters.put("company.id", new SearchFilter("company.id", Operator.EQ, companyId));
		Specification<HrUser> spec = DynamicSpecifications.bySearchFilter(filters.values(), HrUser.class);

		return hrUserDao.findAll(spec, pageRequest);
	}

	@Transactional(readOnly = false)
	public void registerUser(HrUser user) {
		entryptPassword(user);
		user.setRoles("hr");
		user.setRegisterDate(dateProvider.getDate());

		hrUserDao.save(user);
	}

	@Transactional(readOnly = false)
	public void updateUser(HrUser user) {
		if (StringUtils.isNotBlank(user.getPlainPassword())) {
			entryptPassword(user);
		}
		hrUserDao.save(user);
	}

	@Override
	@Transactional(readOnly = false)
	public void deleteUser(Long id) {
		if (isSupervisor(id)) {
			logger.warn("操作员{}尝试删除超级管理员用户", getCurrentUserName());
			throw new ServiceException("不能删除超级管理员用户");
		}
		hrUserDao.delete(id);
	}
}
